<?php

class EasemobUtility {

	public static  $client_id = 'YXA6aa0ScKopEeaCg-fTa36DdQ';
	public static  $client_secret = 'YXA6K-OBnBvTyBnAjL-iD_4jDk52hK0';
	
	public static  $url = "https://a1.easemob.com/1167161114178098/blkappv1";
	public static  $token = '';
	
	public static function token(){
	    $token = Cache::read('easemob_token');
	    if($token === false){
	        $url = self::$url . "/token";
	        $data = array(
	            'grant_type' => 'client_credentials',
	            'client_id' => self::$client_id,
	            'client_secret' => self::$client_secret
	        );
	        $rs = self::curl($url, $data);
	        
	        $token = $rs['access_token'];
	        if($token) {
	            Cache::write('easemob_token', $token,'default',$rs['expires_in']-100);
	        }
	    }
	    return $token;
	}
	
	/*
	 * 注册IM用户(授权注册)
	 */
	public static function register($username, $password, $nickname)
	{
	    $url = self::$url . "/users";
	    $data = array(
	        'username' => $username,
	        'password' => $password,
	        'nickname' => $nickname
	    );
	    $header = array(
	        'Content-Type: application/json',
	        'Authorization: Bearer ' . self::token()
	    );
	    $ret = self::curl($url, $data, $header, "POST");
	    CakeLog::debug('easemob register:'.json_encode($ret)." data:".json_encode($data));
	    return $ret;
	}
    /*
     * 给IM用户的添加好友
     */
    public static function setPassword($username, $newpassword)
    {
        $url = self::$url . "/users/${username}/password";
        $header = array(
            'Authorization: Bearer ' . self::token()
        );
        $data = array(
            'newpassword' => $newpassword,
        );
        return self::curl($url, $data, $header, "POST");
    }

	/*
	 * 给IM用户的添加好友
	 */
	public static function contacts($owner_username, $friend_username)
	{
	    $url = self::$url . "/users/${owner_username}/contacts/users/${friend_username}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "POST");
	}
	/*
	 * 解除IM用户的好友关系
	 */
	public static function contacts_delete($owner_username, $friend_username)
	{
	    $url = self::$url . "/users/${owner_username}/contacts/users/${friend_username}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "DELETE");
	}
	/*
	 * 查看好友
	 */
	public static function contacts_user($owner_username)
	{
	    $url = self::$url . "/users/${owner_username}/contacts/users";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "GET");
	}
	
	/* 发送文本消息 */
	public static function sendMsg($msgtype, $from, $receivers, $msg,$ext = array())
	{
	    $url = self::$url . "/messages";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    if(!is_array($receivers)) {
	        $receivers = array($receivers);
	    }
	    else{
	        $receivers = array_values($receivers);
	    }
	    $data = array(
	        'target_type' => $msgtype, ////users 给用户发消息。chatgroups: 给群发消息，chatrooms: 给聊天室发消息
	        'target' => $receivers,
	        'msg' => $msg,
	        'from' => $from,
	        'ext' => $ext
	    );
	    return self::curl($url, $data, $header, "POST");
	}
	
	/* 发送文本消息 */
	public static function sendUserText($sender, $receiver, $msg)
	{
	    $url = self::$url . "/messages";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    $data = array(
	        'target_type' => 'users',
	        'target' => array(
	            '0' => $receiver
	        ),
	        'msg' => array(
	            'type' => "txt",
	            'msg' => $msg
	        ),
	        'from' => $sender,
	        'ext' => array(
	            'attr1' => 'v1',
	            'attr2' => "v2"
	        )
	    );
	    return self::curl($url, $data, $header, "POST");
	}
	/* 查询离线消息数 获取一个IM用户的离线消息数 */
	public static function msg_count($owner_username)
	{
	    $url = self::$url . "/users/${owner_username}/offline_msg_count";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "GET");
	}
	
	/*
	 * 获取IM用户[单个]
	 */
	public static function user_info($username)
	{
	    $url = self::$url . "/users/${username}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "GET");
	}
	/*
	 * 获取IM用户[批量]
	 */
	public static function user_infos($limit)
	{
	    $url = self::$url . "/users?${limit}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "GET");
	}
	/*
	 * 重置IM用户密码
	 */
	public static function user_update_password($username, $newpassword)
	{
	    $url = self::$url . "/users/${username}/password";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    $data['newpassword'] = $newpassword;
	    return self::curl($url, $data, $header, "PUT");
	}
	
	/*
	 * 删除IM用户[单个]
	 */
	public static function user_delete($username)
	{
	    $url = self::$url . "/users/${username}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, "", $header, "DELETE");
	}
	/*
	 * 修改用户昵称
	 */
	public static function user_update_nickname($username, $nickname)
	{
	    $url = self::$url . "/users/${username}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    $data['nickname'] = $nickname;
	    return self::curl($url, $data, $header, "PUT");
	}
	
	/*
	 * 创建群
	 */
	public static function chatgroups($group)
	{
	    $url = self::$url . "/chatgroups";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    
// 	        "groupname":"testrestgrp12", //群组名称，此属性为必须的
// 	        "desc":"server create group", //群组描述，此属性为必须的
// 	        "public":true, //是否是公开群，此属性为必须的
// 	        "maxusers":300, //群组成员最大数（包括群主），值为数值类型，默认值200，最大值2000，此属性为可选的
// 	        "approval":true, //加入公开群是否需要批准，默认值是false（加入公开群不需要群主批准），此属性为必选的，私有群必须为true
// 	        "owner":"jma1", //群组的管理员，此属性为必须的

	    $group = array_merge(array('public'=>true,'approval'=>false,'maxusers'=>2000),$group);
	    return self::curl($url, $group, $header, "POST");
	}
	
	public static function edit_group($groupid,$name,$description='')
	{
	    $url = self::$url . "/chatgroups/".$groupid;
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	     
	    // 	        "groupname":"testrestgrp12", //群组名称，此属性为必须的
	    // 	        "desc":"server create group", //群组描述，此属性为必须的
	    // 	        "public":true, //是否是公开群，此属性为必须的
	    // 	        "maxusers":300, //群组成员最大数（包括群主），值为数值类型，默认值200，最大值2000，此属性为可选的
	    // 	        "approval":true, //加入公开群是否需要批准，默认值是false（加入公开群不需要群主批准），此属性为必选的，私有群必须为true
	    // 	        "owner":"jma1", //群组的管理员，此属性为必须的
	
	    $group = array('groupname'=>$name,'description'=> $description.' '.$name,'maxusers'=>2000);
	    return self::curl($url, $group, $header, "PUT");
	}
	
	public static function change_group_own($groupid,$owner)
	{
	    $url = self::$url . "/chatgroups/".$groupid;
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    $group = array('newowner'=>$owner);
	    return self::curl($url, $group, $header, "PUT");
	}
	
	public static function delete_group($groupid)
	{
	    $url = self::$url . "/chatgroups/".$groupid;
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, null, $header, "DELETE");
	}
	/**
	 * 加入群
	 * @param unknown $group_id
	 * @param unknown $userid
	 * @return mixed
	 */
	
	public static function group_member($group_id,$userid){
	    
	    $url = self::$url . "/chatgroups/{$group_id}/users/{$userid}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	     
	    return self::curl($url, null, $header, "POST"); // 此处无参数接口要求用post方式
	    
	}
	
	/**
	 * 用户退出群。
	 * @param unknown $group_id
	 * @param unknown $userid
	 */
	public static function delete_group_member($group_id,$userid){
	     
	    $url = self::$url . "/chatgroups/{$group_id}/users/{$userid}";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	
	    return self::curl($url, null, $header, "DELETE"); // 此处无参数接口要求用post方式
		  
	}
	
	public static function user_groups($user_id) {
	    $url = self::$url . "/users/{$user_id}/joined_chatgroups";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, null, $header, "GET");
	}
	
	public static function all_groups(){
	    $url = self::$url . "/chatgroups";
	    $header = array(
	        'Authorization: Bearer ' . self::token()
	    );
	    return self::curl($url, null, $header, "GET");
	}
	/*
	 *
	 * curl
	 */
	public static  function curl($url, $data, $header = false, $method = "POST")
	{
	    $ch = curl_init($url);
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    if ($header) {
	        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	    }
	    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
	    if ($data) {
	        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
	    }
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    $ret = curl_exec($ch);
	    
	    $rs = json_decode($ret, true);
	    return $rs;
	}
	
}
?>